package com.xb.loan.cashier.biz.util;

import com.xb.loan.cashier.biz.pay.bankcomm.BankcommConst;
import com.xb.loan.util.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.Map.Entry;

public class XMLUtil {
	
	public static Map<String, Object> parse(byte[] data) {
		Map<String, Object> map = null ;
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(new ByteArrayInputStream(data));
			Element root = doc.getRootElement();
			map = Iterator(root);
		} catch (DocumentException e) {
			e.printStackTrace();   
		}
		
        return null == map ? new HashMap<String, Object>() : map;
    }
	
	@SuppressWarnings("unchecked")
	private static Map<String, Object> Iterator(Element root) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Element> listEl = root.elements();
		for(Element element : listEl) {
			if(StringUtils.isEmpty(element.getTextTrim())) {
				map.put(element.getName(), Iterator(element));
			} else {
				if(!element.getName().equals("param")) {
					map.put(element.getName(), element.getText());
				} else {
					map.put(element.attributeValue("name"), element.getText());
				}
			}
		}
		return map.isEmpty() ? null : map;
	}
	
	private static String convertXml(Map<String , Object> arr){
		StringBuffer sb = new StringBuffer();
		Iterator<Entry<String, Object>> iter = arr.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, Object> entry = iter.next();
            String key = entry.getKey();
            Object val = entry.getValue();
            sb.append("<" + key + ">");
            sb.append(val);
            sb.append("</" + key + ">");
        }
        return sb.toString();
	}
	
	public static String mapToXml(Map<String , Object> arr) {
	    StringBuffer sb = new StringBuffer("<xml>");
	    sb.append(convertXml(arr));
        sb.append("</xml>");
        return sb.toString();
    }
	
	public static String mapToXml(Map<String, LinkedHashMap<String, Object>> params, String encoding){
		StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\""+encoding+"\" ?>");
		sb.append("<Document>");
		Map<String, Object> headMap = params.get(BankcommConst.HEAD);
		if (headMap!=null && headMap.size()>0) {
			sb.append("<Head>");
			sb.append(convertXml(headMap));
			sb.append("</Head>");
		}
		Map<String, Object> bodyMap = params.get(BankcommConst.BODY);
		if (bodyMap!=null && bodyMap.size()>0) {
			sb.append("<Body>");
			sb.append(convertXml(bodyMap));
			sb.append("</Body>");
		}
		sb.append("</Document>");
		return sb.toString();
	}
	
}
   
